import 'dart:ui';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/services.dart';
import 'package:flutter_native_image/flutter_native_image.dart';
import 'package:magic_car/UI/Loading.dart';
import 'package:magic_car/UI/mykeyboard.dart';
import 'package:magic_car/baoxiu/brandselect.dart';
import 'package:magic_car/baoxiu/cartype.dart';
import 'package:magic_car/jiance/papularInspects.dart';
import 'package:magic_car/jiance/start.dart';
import 'package:magic_car/user/drawboard.dart';
import 'package:magic_car/user/signname.dart';
import 'package:magic_car/util/galleryphotoview.dart';
import 'package:magic_car/zhanshi/cheyuandetail.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:toast/toast.dart';
import 'package:flutter/material.dart';
import 'package:magic_car/util/HttpHelper.dart';
import 'package:image_picker/image_picker.dart';
import 'dart:io';
import 'package:date_format/date_format.dart';
import 'package:webview_flutter/webview_flutter.dart';

class EditUserPage extends StatefulWidget {
  EditUserPage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => new _MyHomePageState();
}
//  Navigator.of(context)
//                           .push(new MaterialPageRoute(builder: (_) {
//                         return new DrawingBoardPage();
//                       })).then((param) {
//                         reloaduserinfo();
//                       });
class _MyHomePageState extends State<EditUserPage> {
  String pwdData = '输入车牌';
  final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();

  // VoidCallback：没有参数并且不返回数据的回调
  VoidCallback _showBottomSheetCallback;

  // TextEditingController _nametroller = new TextEditingController();
  // TextEditingController _agetroller = new TextEditingController();
  // TextEditingController _mobiletroller = new TextEditingController();
  // TextEditingController _validtroller = new TextEditingController();
  // TextEditingController _idcardtroller = new TextEditingController();
  // TextEditingController _expricetroller = new TextEditingController();
  // TextEditingController _passtroller = new TextEditingController();
  // TextEditingController _confirmpasstroller = new TextEditingController();
  List formList;
  bool agreen = false;
  File _image;
  String card_z = '';
  String card_f = '';
  bool select_img = false;
  String status = "";
  List imgs = new List();
  List img_url = new List();
  TextEditingController car_num = new TextEditingController();
  TextEditingController car_price = new TextEditingController();
  TextEditingController num_km = new TextEditingController();
  TextEditingController people = new TextEditingController();
  TextEditingController mobile = new TextEditingController();
  TextEditingController address = new TextEditingController();
  TextEditingController desrible = new TextEditingController();
  bool hassigned = false;
  var userinfo;
  initState() {
    super.initState();

    formList = [
      {
        "title": '头像',
        'sub_title': '云A00001云A00001云A00',
        'sub_color': Color.fromRGBO(27, 182, 251, 1),
        'type': 7,
        'bottom': 1.0,
        'value': '',
        'code': 'avatar',
        'ctroller': car_price,
        'text_type': 4,
        'max_length': 0
      },
      {
        "title": '个人半身照',
        'sub_title': '云A00001云A00001云A00',
        'sub_color': Color.fromRGBO(27, 182, 251, 1),
        'type': 11,
        'bottom': 1.0,
        'value': '',
        'code': 'half_img',
        'ctroller': car_price,
        'text_type': 4,
        'max_length': 0
      },

      {
        "title": '姓名',
        'sub_title': '云A00001云A00001云A00',
        'sub_color': Color.fromRGBO(27, 182, 251, 1),
        'type': 1,
        'bottom': 1.0,
        'value': '',
        'code': 'name',
        'ctroller': car_price,
        'text_type': 1,
        'max_length': 0
      },
      {
        "title": '电话',
        'sub_title': '云A00001云A00001云A00',
        'sub_color': Color.fromRGBO(27, 182, 251, 1),
        'type': 1,
        'bottom': 1.0,
        'value': '',
        'code': 'mobile',
        'ctroller': people,
        'text_type': 2,
        'max_length': 5
      },
      {
        "title": '身份证号码',
        'sub_title': '云A00001云A00001云A00',
        'sub_color': Color.fromRGBO(27, 182, 251, 1),
        'type': 1,
        'bottom': 1.0,
        'value': '',
        'code': 'idcard',
        'ctroller': people,
        'text_type': 2,
        'max_length': 5
      },
      {
        "title": '工作年限',
        'sub_title': '云A00001云A00001云A00',
        'sub_color': Color.fromRGBO(27, 182, 251, 1),
        'type': 1,
        'bottom': 1.0,
        'value': '',
        'code': 'lengthofservice',
        'ctroller': people,
        'text_type': 2,
        'max_length': 5
      },
      {
        "title": '入驻协议',
        'sub_title': '云A00001云A00001云A00',
        'sub_color': Color.fromRGBO(27, 182, 251, 1),
        'type': 1,
        'bottom': 1.0,
        'value': '',
        'code': 'agreenment',
        'ctroller': people,
        'text_type': 2,
        'max_length': 5
      },
      {
        "title": '身份证正面',
        'sub_title': '云A00001云A00001云A00',
        'sub_color': Color.fromRGBO(27, 182, 251, 1),
        'type': 10,
        'bottom': 1.0,
        'value': '',
        'code': 'idcardfronturl',
        'ctroller': people,
        'text_type': 2,
        'max_length': 5
      },
       {
        "title": '身份证反面',
        'sub_title': '云A00001云A00001云A00',
        'sub_color': Color.fromRGBO(27, 182, 251, 1),
        'type': 10,
        'bottom': 1.0,
        'value': '',
        'code': 'idcardbackurl',
        'ctroller': people,
        'text_type': 2,
        'max_length': 5
      },
      // {
      //   "title": '区域',
      //   'sub_title': '云A00001云A00001云A00',
      //   'sub_color': Color.fromRGBO(27, 182, 251, 1),
      //   'type': 1,
      //   'bottom': 1.0,
      //   'value': '',
      //   'code': 'distict',
      //   'ctroller':mobile,
      //   'text_type':2,
      //   'max_length':11
      // },

      // {
      //   "title": '详细地址',
      //   'sub_title': '云A00001云A00001云A00',
      //   'sub_color': Color.fromRGBO(27, 182, 251, 1),
      //   'type': 1,
      //   'bottom': 1.0,
      //   'value': '',
      //   'code': 'address',
      //   'ctroller':mobile,
      //   'text_type':2,
      //   'max_length':11
      // },

      // {
      //   "title": '车源简介',
      //   'sub_title': '云A00001云A00001云A00',
      //   'sub_color': Color.fromRGBO(27, 182, 251, 1),
      //   'type': 5,
      //   'bottom': 10.0,
      //   'value': '',
      //   'code': 'car_descrble',
      //   'ctroller':desrible
      // },
    ];
    //imgs.add({'url':'''order["status"].toString() != "3"'''}'resource/images/user/upimg.png');
    imgs = [];
    loaduserinfo();
  }

  loaduserinfo() async {
    SharedPreferences pref = await SharedPreferences.getInstance();
    Map<String, String> map = new Map();
    map["id"] = pref.getString('uid');

    HttpHelper.post(HttpHelper.API_Userinfo, (data) async {
      if (data != null) {
        print(data);
        //Toast.show(data["msg"], context);

        if (data["code"].toString() == "1") {
          // if (data["info"]["avatar"].length != 0) {
          //   setState(() {
          //     avatar = data["info"]["avatar"];
          //   });
          // }

          if(data['info']['half_img']==null){
            print('没有半身照');
          }
          if(data["info"]["agreenment"]==null || data["info"]["agreenment"]==""){
           // Toast.show("未签协议", context);
          }
          var info = data["info"];
          for (var item in formList) {
            var code = item['code'];
            
            item['value'] = info[code];
            if(code=="agreenment"){
              if(info[code]==null|| info[code]==""){
                item['value']="点击签约";
                setState(() {
                  hassigned = false;
                });
              }else {
                item['value']="查看协议";
                  setState(() {
                  hassigned = true;
                });
              }
            }
            // if(code=='distict'){
            //   item['value']=info['provinceName']+info['cityName']+info['areaName'];
            // }else
            // item['value'] = info[code];
          }

          setState(() {
            formList = formList;
            // avatar =
            //     data["info"]["avatar"] == null ? "" : data["info"]["avatar"];
            // loadinfo = true;
             userinfo = data["info"];
          });
          //pref.setStringList('userinfo', data["info"]);

        }
      }
    }, params: map);
  }

  Widget layout() {
    List<Widget> tiles = [];
    Widget content;
    tiles.add(Align(
        alignment: Alignment.centerLeft,
        child: Padding(
            padding: new EdgeInsets.fromLTRB(10, 0, 0, 10),
            child: Text('基本信息'))));
    for (var item in formList) {
      var type = item["type"];
      if (type == 1) {
        //输入框
        tiles.add(inputWidget(item));
      } else if (type == 2) {
        //时间选择
        tiles.add(dateSelect(item));
      } else if (type == 3) {
        //类型选择
        tiles.add(cartype(item));
      } else if (type == 4) {
        //图片
        tiles.add(imagUp(item));
      } else if (type == 5) {
        tiles.add(textarea(item));
      } else if (type == 6) {
        tiles.add(carNuminput(item));
      } else if (type == 7) {
        tiles.add(avatar(item));
      }else if(type==10){
        tiles.add(cardWidget(item));
      }else if(type==11){
         tiles.add(half_img(item));
      }else if(type==12){

      }
    }
    // var btn = new SizedBox(
    //     width: double.infinity,
    //     height: 50,
    //     child: new FlatButton(
    //       child: Text('立即申请入驻'),
    //       textColor: Colors.white,
    //       color: Colors.white,
    //       //color: Color.fromRGBO(27, 182, 251, 1),
    //       onPressed: () {
    //         regist();
    //       },
    //     ));
    var btn = new Container(
        color: Color.fromRGBO(239, 239, 239, 1),
        //color:Colors.white,
        child: new Padding(
            padding: new EdgeInsets.fromLTRB(10, 20, 20, 0),
            child: new Material(
              color: Color.fromRGBO(239, 239, 239, 1),
              //INK可以实现装饰容器
              child: new Ink(
                //用ink圆角矩形
                //color: Color.fromRGBO(239, 239, 239, 1),
                decoration: new BoxDecoration(
                  //背景

                  color: Color.fromRGBO(255, 204, 48, 1),
                  //设置四周圆角 角度
                  borderRadius: BorderRadius.all(Radius.circular(18.0)),
                  //设置四周边框
                  border: new Border.all(
                      width: 1, color: Color.fromRGBO(255, 204, 48, 1)),
                ),
                child: new InkWell(

                    //圆角设置,给水波纹也设置同样的圆角
                    //如果这里不设置就会出现矩形的水波纹效果
                    borderRadius: new BorderRadius.circular(15.0),
                    //设置点击事件回调
                    onTap: () {
                      submit();
                    },
                    child: Container(
                      //设置 child 居中
                      alignment: Alignment(0, 0),
                      height: 36,
                      //color: Color.fromRGBO(239, 239, 239, 1),
                      width: double.infinity,
                      child: Text(
                        "下一步",
                        style: TextStyle(color: Colors.white),
                      ),
                    )),
              ),
            )));
    // tiles.add(btn);
    content = new Padding(
        padding: new EdgeInsets.fromLTRB(0, 0, 0, 10),
        child: new Column(
            mainAxisAlignment: MainAxisAlignment.start,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: tiles //重点在这里，因为用编辑器写Column生成的children后面会跟一个<Widget>[]，
            //此时如果我们直接把生成的tiles放在<Widget>[]中是会报一个类型不匹配的错误，把<Widget>[]删了就可以了
            ));
    return content;
  }
  //车牌键盘布局

  Widget carNuminput(item) {
    DateTime initialDate = DateTime.now();
    Widget content = Padding(
        padding: new EdgeInsets.fromLTRB(0, 0, 0, item["bottom"]),
        child: Container(
            color: Colors.white,
            height: 50,
            child: new GestureDetector(
              behavior: HitTestBehavior.opaque,
              onTap: () {
                FocusScope.of(context).requestFocus(FocusNode());
                _showBottomSheetCallback();
              },
              child: new Row(
                children: <Widget>[
                  Expanded(
                    child: new Padding(
                      padding: new EdgeInsets.fromLTRB(10, 0, 10, 0),
                      child: RichText(
                        text: TextSpan(
                            text: item["title"],
                            style: TextStyle(
                                fontSize: 15,
                                color: Color.fromRGBO(102, 102, 102, 1)),
                            children: [
                              // TextSpan(
                              //     text: '*',
                              //     style: TextStyle(fontSize: 14, color: Colors.red))
                            ]),
                      ),
                    ),
                    flex: 1,
                  ),
                  Expanded(
                    child: Padding(
                        padding: new EdgeInsets.fromLTRB(10, 0, 30, 0),
                        child:
                            // new GestureDetector(
                            //   onTap: (){
                            //     _showBottomSheetCallback();
                            //   },
                            //   child:
                            Align(
                          alignment: Alignment.centerRight,
                          child:
                              // new GestureDetector(
                              //     child:
                              new Text(pwdData),
                        )),
                    flex: 2,
                  )
                ],
              ),
            )));
    return content;
  }

//提交生成检测订单
  submit() async {
    FocusScope.of(context).requestFocus(FocusNode());
    // LoadingPage loadpage = new LoadingPage(context);
    // loadpage.show();
    print(this.formList);
    Map<String, String> param = new Map();
    for (var i = 0; i < this.formList.length; i++) {
      var item = this.formList[i];
      if (item["code"] != "") {
        var code = item["code"];
        if (item["value"] == "") {
          Toast.show('请填写完整的信息', context);
          return;
          // break;
        }
        param[code] = item["value"].toString();
      }
    }
    String image_Str = '';
    int isupdate = 0;
    for (var i = 0; i < imgs.length; i++) {
      var item = imgs[i];
      print(item);
      if (item['isupdate'] == 1) {
        isupdate++;
      }

      var tempStr = "";
      if (item.containsKey('attachment')) {
        tempStr = item['attachment'];
      }
      if (i == imgs.length - 1) {
        image_Str = image_Str + tempStr;
      } else
        image_Str = image_Str + tempStr + ',';
    }
    if (isupdate == 0) {
      //请上传图片
      Toast.show('请上传图片', context);
      return;
    }
    param["thumb"] = image_Str;
    param["brand_id"] = formList[1]["brand_id"];
    param["cartype_id"] = formList[2]['type_id'];
    param["car_num"] = pwdData;
    // param["price"]=formList[1]["value"].toString();
    // param["contact_people"]=formList[2]["value"].toString();
    // param["contact_mobile"]=formList[3]["value"].toString();
    // param["address"]=formList[4]["value"].toString();
    // param["car_descrble"]=formList[6]["value"].toString();

    SharedPreferences pref = await SharedPreferences.getInstance();

    param["bid"] = pref.getString('uid').toString();
    print(param);

    HttpHelper.post(HttpHelper.API_BussinessSuborder, (data) async {
      //loadpage.close();
      //loadpage.close();
      if (data != null) {
        print(data);
        //Toast.show(data["msg"], context);

        if (data["code"].toString() == "1") {
          showAlert(data["info"].toString());
          //Toast.show('请开始检测', context);
          //清空输入框
          car_num.clear();

          address.clear();
          car_price.clear();
          desrible.clear();
          people.clear();
          mobile.clear();
          for (int i = 0; i < formList.length; i++) {
            formList[i]["value"] = "";
          }
          setState(() {
            formList = formList;
            imgs = [];
            // img_url=[];
          });

          // imgs.add('resource/images/user/upimg.png');

        }
      }
    }, params: param);
  }

  showAlert(id) {
    showDialog<Null>(
      context: context,
      builder: (BuildContext context) {
        return new AlertDialog(
            title: Text('提示!'),
            content: new Text('您的车源已提交，若完成车况检测将会优先置顶展示'),
            actions: <Widget>[
              new FlatButton(
                  onPressed: () {
                    Navigator.of(context).pop();
                    Navigator.of(context)
                        .push(new MaterialPageRoute(builder: (_) {
                      return new Papularinspects(id, 2, {},false);
                    }));
                    //connect();
                    // Navigator.pop(context);
                  },
                  child: new Text(
                    '确定',
                    style: new TextStyle(color: Colors.black),
                  ))
            ]);
      },
    );
  }
  //身份证组件
    //输入框组件
  Widget cardWidget(item) {
    

    Widget content = Padding(
        padding: new EdgeInsets.fromLTRB(0, 0, 0, item["bottom"]),
        child: Container(
          color: Colors.white,
          height: 270,
          child: new Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              new Padding(
                  padding: new EdgeInsets.fromLTRB(10, 10, 10, 0),
                  child: RichText(
                    text: TextSpan(
                        text: item["title"],
                        style: TextStyle(
                            fontSize: 15,
                            color: Color.fromRGBO(102, 102, 102, 1)),
                        children: [
                          // TextSpan(
                          //     text: '*',
                          //     style: TextStyle(fontSize: 14, color: Colors.red))
                        ]),
                  ),
                ),
               
              
                new Padding(
                    padding: new EdgeInsets.fromLTRB(10, 10, 10, 10),
                    child: new Align(
                        alignment: Alignment.center,
                        child:item['value']==""?Container(height: 0,):CachedNetworkImage(imageUrl: item['value'],height: 200)
                        //  Image.network(item['value'],height: 200,)
                         )),
                
            ],
          ),
        ));
    return content;
  }

  List imageModel(data) {
    List img_temp = [
      "https://car3.autoimg.cn/cardfs/product/g1/M09/3F/A8/240x180_0_q95_c42_autohomecar__ChwFqV69W4KAf_AzAAShphUBgV4514.jpg",
      "https://car2.autoimg.cn/cardfs/product/g25/M09/6E/D2/240x180_0_q95_c42_autohomecar__ChwFj169W32Ad5ehAAT2abQFAio994.jpg",
      "https://car2.autoimg.cn/cardfs/product/g25/M08/6E/D2/240x180_0_q95_c42_autohomecar__ChwFj169W3uATe71AASA9ZdptWg816.jpg",
      "https://car2.autoimg.cn/cardfs/product/g25/M0B/73/06/240x180_0_q95_c42_autohomecar__ChsEmF69W3qAYeneAAQeve0abAo167.jpg",
    ];
    List imgList = List();
    for (int x = 0; x < data.length; x++) {
      GalleryExampleItem item = GalleryExampleItem();
      item.id = '$x';
      item.resource = data[x];
      // item.resource = data[x]["url"];
      imgList.add(item);
    }
    print(imgList.first.id);

    return imgList;
  }


  //输入框组件
  Widget inputWidget(item) {
    TextInputType texttype = TextInputType.text;
    if (item['text_type'] == 1) {
      texttype = TextInputType.number;
    } else if (item['text_type'] == 2) {
      texttype = TextInputType.text;
    }

    Widget content = Padding(
        padding: new EdgeInsets.fromLTRB(0, 0, 0, item["bottom"]),
        child:
        InkWell(
          onTap: ()async{
            if(item["code"]=="agreenment"){
             
              if(hassigned){
                 Navigator.of(context).push(new FadeRoute(
                page: GalleryPhotoViewWrapper(
              galleryItems: imageModel([userinfo["agreenment"]]),
              backgroundDecoration: const BoxDecoration(
                color: Colors.black,
              ),
              initialIndex: 1,
            )));
                  //  await Navigator.of(context).push(
                  //             MaterialPageRoute<void>(
                  //               builder: (BuildContext context) {
                  //                 return Scaffold(
                  //                   appBar: AppBar(
                  //                     backgroundColor:Colors.white
                  //                   ),
                  //                   body: Center(
                  //                     child: Container(
                  //                       color: Colors.grey[300],
                  //                       child:CachedNetworkImage(imageUrl: userinfo["agreenment"])
                  //                       // child: WebView(
                  //                       //   initialUrl: userinfo["agreenment"],
                  //                       // ),
                  //                     ),
                  //                   ),
                  //                 );
                  //               },
                  //             ),
                  //           );
              }
              else{
               Navigator.of(context)
                          .push(new MaterialPageRoute(builder: (_) {
                        return new DrawingBoardPage();
                      })).then((param) {
                       loaduserinfo();
                      });
              }
            }
          },
          child:
         Container(
          color: Colors.white,
          height: 50,
          child: new Row(
            children: <Widget>[
              Expanded(
                child: new Padding(
                  padding: new EdgeInsets.fromLTRB(10, 0, 10, 0),
                  child: RichText(
                    text: TextSpan(
                        text: item["title"],
                        style: TextStyle(
                            fontSize: 15,
                            color: Color.fromRGBO(102, 102, 102, 1)),
                        children: [
                          // TextSpan(
                          //     text: '*',
                          //     style: TextStyle(fontSize: 14, color: Colors.red))
                        ]),
                  ),
                ),
                flex: 1,
              ),
              Expanded(
                child: new Padding(
                    padding: new EdgeInsets.fromLTRB(10, 0, 25, 0),
                    child: new Align(
                        alignment: Alignment.centerRight,
                        child: Text(item['value']))),
                flex: 2,
              )
            ],
          ),
        )));
    return content;
  }
  // //输入框组件
  // Widget inputWidget(item) {
  //   TextInputType texttype=TextInputType.text;
  //   if(item['text_type']==1){
  //   texttype = TextInputType.number;
  //   }else if(item['text_type']==2){
  //     texttype = TextInputType.text;
  //   }

  //   Widget content = Padding(
  //       padding: new EdgeInsets.fromLTRB(0, 0, 0, item["bottom"]),
  //       child: Container(
  //         color: Colors.white,
  //         height: 50,
  //         child: new Row(
  //           children: <Widget>[
  //             Expanded(
  //               child: new Padding(
  //                 padding: new EdgeInsets.fromLTRB(10, 0, 10, 0),
  //                 child: RichText(
  //                   text: TextSpan(
  //                       text: item["title"],
  //                       style: TextStyle(
  //                           fontSize: 15,
  //                           color: Color.fromRGBO(102, 102, 102, 1)),
  //                       children: [
  //                         // TextSpan(
  //                         //     text: '*',
  //                         //     style: TextStyle(fontSize: 14, color: Colors.red))
  //                       ]),
  //                 ),
  //               ),
  //               flex: 1,
  //             ),
  //              item["max_length"]>0?
  //             Expanded(

  //               child: new Padding(
  //                   padding: new EdgeInsets.fromLTRB(10, 0, 10, 0),
  //                   child:

  //                   new TextField(
  //                     textAlign: TextAlign.right,
  //                      controller: item["ctroller"],
  //                       maxLength: item["max_length"],maxLengthEnforced: true,

  //                      keyboardType:texttype,
  //     //                  inputFormatters: <TextInputFormatter>[
  //     //      LengthLimitingTextInputFormatter(20)//限制长度
  //     //  ],

  //                     decoration: InputDecoration(
  //                       counterText:"",
  //                       hintText: '请输入' + item["title"],
  //                       border: OutlineInputBorder(
  //                         borderSide: BorderSide.none,
  //                       ),
  //                     ),
  //                     onChanged: (val) {
  //                       setState(() {
  //                         item["value"] = val;
  //                       });
  //                     },
  //                   )
  //                   )
  //                   ,
  //               flex: 2,
  //             )
  //             :Expanded(

  //               child: new Padding(
  //                   padding: new EdgeInsets.fromLTRB(10, 0, 10, 0),
  //                   child:

  //                   new TextField(
  //                     textAlign: TextAlign.right,
  //                      controller: item["ctroller"],

  //                      keyboardType:texttype,
  //     //                  inputFormatters: <TextInputFormatter>[
  //     //      LengthLimitingTextInputFormatter(20)//限制长度
  //     //  ],

  //                     decoration: InputDecoration(
  //                       hintText: '请输入' + item["title"],
  //                       border: OutlineInputBorder(
  //                         borderSide: BorderSide.none,
  //                       ),
  //                     ),
  //                     onChanged: (val) {
  //                       setState(() {
  //                         item["value"] = val;
  //                       });
  //                     },
  //                   )
  //                   )
  //                   ,
  //               flex: 2,
  //             )
  //           ],
  //         ),
  //       ));
  //   return content;
  // }

  //日期选择组件
  Widget dateSelect(item) {
    DateTime initialDate = DateTime.now();
    Widget content = Padding(
        padding: new EdgeInsets.fromLTRB(0, 0, 0, item["bottom"]),
        child: Container(
          color: Colors.white,
          height: 50,
          child: new Row(
            children: <Widget>[
              Expanded(
                child: new Padding(
                  padding: new EdgeInsets.fromLTRB(10, 0, 10, 0),
                  child: RichText(
                    text: TextSpan(
                        text: item["title"],
                        style: TextStyle(
                            fontSize: 15,
                            color: Color.fromRGBO(102, 102, 102, 1)),
                        children: [
                          // TextSpan(
                          //     text: '*',
                          //     style: TextStyle(fontSize: 14, color: Colors.red))
                        ]),
                  ),
                ),
                flex: 1,
              ),
              Expanded(
                child: Padding(
                    padding: new EdgeInsets.fromLTRB(10, 0, 20, 0),
                    child: Align(
                        alignment: Alignment.centerRight,
                        child: new GestureDetector(
                            child: new Text(item["value"]),
                            onTap: () async {
                              final DateTime dateTime = await showDatePicker(
                                context: context,
                                //定义控件打开时默认选择日期
                                initialDate: initialDate,
                                //��义控件最早可以选择的日期
                                firstDate: DateTime(2018, 1),
                                //定义控件最晚可以选择的日期
                                lastDate: DateTime(2050, 1),
                              );

                              if (dateTime != null) {
                                setState(() {
                                  String code = item["code"];
                                  item["value"] = formatDate(
                                      dateTime, [yyyy, "-", mm, "-", dd]);
                                  //formalities[code] = item["value"];
                                });
                              }
                            }))),
                flex: 2,
              )
            ],
          ),
        ));
    return content;
  }

  //车辆类型组件
  Widget cartype(item) {
    Widget content = Padding(
        padding: new EdgeInsets.fromLTRB(0, 0, 0, item["bottom"]),
        child: Container(
            color: Colors.white,
            height: 50,
            child: new GestureDetector(
              behavior: HitTestBehavior.opaque,
              onTap: () {
                FocusScope.of(context).requestFocus(FocusNode());
                //print('选择车型');
                if (item.containsKey("brand_id")) {
                  Navigator.of(context)
                      .push(new MaterialPageRoute(builder: (_) {
                    return new BrandSelectRoute(item);
                  }));
                } else {
                  Navigator.of(context)
                      .push(new MaterialPageRoute(builder: (_) {
                    return new CartypeSelectRoute(
                        item, formList[1]["brand_id"], '0');
                  }));
                }
              },
              child: new Row(
                mainAxisAlignment: MainAxisAlignment.end,
                children: <Widget>[
                  Expanded(
                    child: new Padding(
                      padding: new EdgeInsets.fromLTRB(10, 0, 10, 0),
                      child: RichText(
                        text: TextSpan(
                            text: item["title"],
                            style: TextStyle(
                                fontSize: 15,
                                color: Color.fromRGBO(102, 102, 102, 1)),
                            children: [
                              // TextSpan(
                              //     text: '*',
                              //     style: TextStyle(fontSize: 14, color: Colors.red))
                            ]),
                      ),
                    ),
                  ),
                  //  Expanded(
                  //   child:
                  new Padding(
                    padding: new EdgeInsets.fromLTRB(10, 0, 0, 0),
                    child: RichText(
                      text: TextSpan(
                          text: item["value"],
                          style: TextStyle(
                              fontSize: 15,
                              color: Color.fromRGBO(102, 102, 102, 1)),
                          children: [
                            // TextSpan(
                            //     text: '*',
                            //     style: TextStyle(fontSize: 14, color: Colors.red))
                          ]),
                    ),
                  ),

                  //),
                  // Expanded(
                  //   child:
                  Padding(
                      padding: new EdgeInsets.fromLTRB(10, 0, 20, 0),
                      child: Align(
                          alignment: Alignment.centerRight,
                          child: Image.asset(
                            'resource/images/user/detail.png',
                            height: 20,
                          ))),

                  // )
                ],
              ),
            )));
    return content;
  }
  showdialog(index) {
    showModalBottomSheet(
        context: context,
        builder: (BuildContext context) {
          return Padding(
              padding: new EdgeInsets.fromLTRB(0, 0, 0, 0),
              child: Container(
                height: 170,
                child: new Column(children: <Widget>[
                  new Container(
                      decoration: new BoxDecoration(
                          border: Border(
                              bottom: BorderSide(
                                  width: 1, color: Color(0xffe5e5e5)))),
                      height: 50,
                      child: Center(
                          child: Text('上传图片',
                              style: TextStyle(fontSize: 16)))),

                   new Container(
                      decoration: new BoxDecoration(
                          border: Border(
                              bottom: BorderSide(
                                  width: 1, color: Color(0xffe5e5e5)))),
                      height: 40,
                      child: new GestureDetector(
                          behavior: HitTestBehavior.opaque,
                          onTap: () async {
                            // Navigator.pop(context);
                           // confirm();
                            Navigator.pop(context);
                           showDialog(
                        context: context,
                        builder: (BuildContext context) {
                          return new AlertDialog(
                            title: new Text('上传示例'),
                            content: new SingleChildScrollView(
                                child: new Image.asset('resource/images/user/banshenzhao.png')),
                            // actions: <Widget>[
                            //   new FlatButton(
                            //     child: new Text('确定'),
                            //     onPressed: () {
                            //       Navigator.of(context).pop();
                            //     },
                            //   ),
                            // ],
                          );
                        },
                      );
                          },
                          child: Center(
                              child: Text('查看示例图片',
                                  style: TextStyle(
                                      fontSize: 16, color: Colors.red))))),            
                  new Container(
                      decoration: new BoxDecoration(
                          border: Border(
                              bottom: BorderSide(
                                  width: 1, color: Color(0xffe5e5e5)))),
                      height: 40,
                      child: new GestureDetector(
                          behavior: HitTestBehavior.opaque,
                          onTap: () async {
                            // Navigator.pop(context);
                           // confirm();
                            Navigator.pop(context);
                           getimgs(1, index);
                          },
                          child: Center(
                              child: Text('相册',
                                  style: TextStyle(
                                      fontSize: 16, color: Colors.red))))),
                  new Container(
                      height: 40,
                      child: new GestureDetector(
                          behavior: HitTestBehavior.opaque,
                          onTap: () {
                            Navigator.pop(context);
                            getimgs(0, index);
                          },
                          child: Center(
                              child:
                                  Text('相机', style: TextStyle(fontSize: 16))))),
                ]),
              ));
        });
  }
//半身照
  Widget half_img(item) {
    Widget content = Padding(
        padding: new EdgeInsets.fromLTRB(0, 0, 0, item["bottom"]),
        child: Container(
            color: Colors.white,
            height: 100,
            child: new GestureDetector(
              behavior: HitTestBehavior.opaque,
              onTap: () {
                showdialog(1);
              },
              child: new Row(
                mainAxisAlignment: MainAxisAlignment.end,
                children: <Widget>[
                  Expanded(
                    child: new Padding(
                      padding: new EdgeInsets.fromLTRB(10, 0, 10, 0),
                      child: RichText(
                        text: TextSpan(
                            text: item["title"]+'（请按照示例图片上传，宽:高=2:3）',
                            style: TextStyle(
                                fontSize: 14,
                                color: Color.fromRGBO(102, 102, 102, 1)),
                            children: [
                              // TextSpan(
                              //     text: '*',
                              //     style: TextStyle(fontSize: 14, color: Colors.red))
                            ]),
                      ),
                    ),
                  ),
                 
                  Padding(
                      padding: new EdgeInsets.fromLTRB(10, 0, 20, 0),
                      child: Align(
                          alignment: Alignment.centerRight,
                          child: Container(
                              width: 80,
                              height: 80,
                              child:
                              
                               ClipRRect(
                                borderRadius: BorderRadius.circular(0),
                                child:item['value']==""?Image.asset( "resource/images/user/banshenzhao.png"):CachedNetworkImage(imageUrl: item['value'])
                                // child: FadeInImage.assetNetwork(
                                //   placeholder: "resource/images/user/banshenzhao.png",
                                //   image: item['value'],
                                //   fit: BoxFit.contain
                                // ),
                              ))
                              )),

                  // )
                ],
              ),
            )));
    return content;
  }
  //头像
  //车辆类型组件
  Widget avatar(item) {
    Widget content = Padding(
        padding: new EdgeInsets.fromLTRB(0, 0, 0, item["bottom"]),
        child: Container(
            color: Colors.white,
            height: 100,
            child: new GestureDetector(
              behavior: HitTestBehavior.opaque,
              onTap: () {
                showdialog(0);
              },
              child: new Row(
                mainAxisAlignment: MainAxisAlignment.end,
                children: <Widget>[
                  Expanded(
                    child: new Padding(
                      padding: new EdgeInsets.fromLTRB(10, 0, 10, 0),
                      child: RichText(
                        text: TextSpan(
                            text: item["title"],
                            style: TextStyle(
                                fontSize: 15,
                                color: Color.fromRGBO(102, 102, 102, 1)),
                            children: [
                              // TextSpan(
                              //     text: '*',
                              //     style: TextStyle(fontSize: 14, color: Colors.red))
                            ]),
                      ),
                    ),
                  ),
                 
                  Padding(
                      padding: new EdgeInsets.fromLTRB(10, 0, 20, 0),
                      child: Align(
                          alignment: Alignment.centerRight,
                          child: Container(
                              width: 60,
                              height: 60,
                              child: ClipRRect(
                                borderRadius: BorderRadius.circular(30),
                                child: item['value']==""?Image.asset("resource/images/user/user6.png"):CachedNetworkImage(imageUrl: item['value'],fit:BoxFit.cover),

                                // child: FadeInImage.assetNetwork(
                                //   placeholder: "resource/images/user/user6.png",
                                //   image: item['value'],
                                //   fit: BoxFit.cover,
                                // ),
                              )))),

                  // )
                ],
              ),
            )));
    return content;
  }

  //图片上传组件
  Widget imagUp(item) {
    Widget content = Padding(
        padding: new EdgeInsets.fromLTRB(0, 0, 0, item["bottom"]),
        child: Container(
          color: Colors.white,
          width: double.infinity,
          // height: 160,
          child: new Column(
            mainAxisAlignment: MainAxisAlignment.start,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              new Padding(
                padding: new EdgeInsets.fromLTRB(10, 10, 10, 0),
                child: RichText(
                  text: TextSpan(
                      text: item["title"],
                      style: TextStyle(
                          fontSize: 15,
                          color: Color.fromRGBO(102, 102, 102, 1)),
                      children: [
                        // TextSpan(
                        //     text: '*',
                        //     style: TextStyle(fontSize: 14, color: Colors.red))
                      ]),
                ),
              ),
              Padding(
                  padding: new EdgeInsets.fromLTRB(0, 0, 0, 0),
                  child: Container(
                      color: Colors.white,
                      // height: 100,
                      child: new Column(
                          mainAxisAlignment: MainAxisAlignment.start,
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: <Widget>[
                            new Container(child: buildCImgs())
                          ]))),

              //  Expanded(
              //   child:
            ],
          ),
        ));
    return content;
  }

  Widget textarea(item) {
    Widget content = Padding(
        padding: new EdgeInsets.fromLTRB(0, 0, 0, item["bottom"]),
        child: Container(
          color: Colors.white,
          width: double.infinity,
          // height: 160,
          child: new Column(
            mainAxisAlignment: MainAxisAlignment.start,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              new Padding(
                padding: new EdgeInsets.fromLTRB(10, 10, 10, 0),
                child: RichText(
                  text: TextSpan(
                      text: item["title"],
                      style: TextStyle(
                          fontSize: 15,
                          color: Color.fromRGBO(102, 102, 102, 1)),
                      children: [
                        // TextSpan(
                        //     text: '*',
                        //     style: TextStyle(fontSize: 14, color: Colors.red))
                      ]),
                ),
              ),
              Padding(
                  padding: new EdgeInsets.fromLTRB(0, 0, 0, 0),
                  child: Container(
                      color: Colors.white,
                      // height: 100,
                      child: new Column(
                          mainAxisAlignment: MainAxisAlignment.start,
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: <Widget>[
                            new Container(
                                child: new TextField(
                              maxLines: 10,
                              textAlign: TextAlign.left,
                              controller: item["ctroller"],
                              decoration: InputDecoration(
                                hintText: '请输入' + item["title"],
                                border: OutlineInputBorder(
                                  borderSide: BorderSide.none,
                                ),
                              ),
                              onChanged: (val) {
                                item["value"] = val;
                              },
                            ))
                          ]))),

              //  Expanded(
              //   child:
            ],
          ),
        ));
    return content;
  }

  Widget buildCImgs() {
    List<Widget> tiles = [];

    Widget content;

    List items = imgs;
    print(items);
    // print('图片数组长度'+items.isNotEmpty.toString());
    if (items.length > 0) {
      // tiles.add(new Container(
      //       padding: new EdgeInsets.fromLTRB(60, 0, 20, 0),)
      for (var i = 0; i < items.length; i++) {
        //List temp1 = items[i] as List;
        tiles.add(new Container(
            width: 120,
            height: 160,
            padding: new EdgeInsets.fromLTRB(0, 0, 0, 0),
            child: Padding(
                padding: new EdgeInsets.fromLTRB(5, 10, 0, 10),
                child: GestureDetector(
                    onTap: () {
                      FocusScope.of(context).requestFocus(FocusNode()); //隐藏键盘
                      print('点击查看图片');
                      getImage(i);
                      // if (i == items.length - 1) {
                      //   getImage();
                      // }
                      // Navigator.of(context).push(
                      //   NinePicture(items, i),
                      //);
                    },
                    child: new Column(
                      children: <Widget>[
                        items[i]['isupdate'] == 0
                            ? Image.asset('resource/images/user/upimg.png',
                                width: 100, height: 100)
                            : CachedNetworkImage(
                                imageUrl: items[i]['url'],
                                width: 100,
                                height: 100,
                              ),
                        //Image.network(items[i]['url'], width: 100, height: 100),
                        Center(child: Text(items[i]['name']))
                      ],
                    )))));
      }
    }
    content = new Wrap(
        children: tiles //重点在这里，因为用编辑器写Column生成的children后面会跟一个<Widget>[]，
        //此时如果我们直接把生成的tiles放在<Widget>[]中是会报一个类型不匹配的错误，把<Widget>[]删了就可以了
        );
    return content;
  }
//   //选择图片
//   getimgs(type, card) async {
//     if (type == 1) {
//       var image = await ImagePicker.pickImage(source: ImageSource.gallery);

//       setState(() {
//         _image = image;
//         select_img = true;
//       });
//     } else {
//       var image = await ImagePicker.pickImage(source: ImageSource.camera);

//       setState(() {
//         _image = image;
//         select_img = true;
//       });
//     }
//     if (_image == null) return;
//     Map<String, String> map = new Map();

//     HttpHelper.upLoadImage(_image, (data) {
//       if (card == 1) {
//         setState(() {
//           card_z = data["url"];
//         });
//       } else {
//         card_f = data["url"];
//       }
//     }, params: map);
//   }

// //选择图片�����
//   Future getImage(type) async {
//     showDialog(
//         context: context,
//         builder: (BuildContext context) {
//           return new SimpleDialog(
//             title: new Text('选择'),
//             children: <Widget>[
//               new SimpleDialogOption(
//                 child: new Text('相机'),
//                 onPressed: () {
//                   Navigator.pop(context);
//                   getimgs(0, type);
//                 },
//               ),
//               new SimpleDialogOption(
//                 child: new Text('相册'),
//                 onPressed: () {
//                   Navigator.pop(context);
//                   getimgs(1, type);
//                 },
//               )
//             ],
//           );
//         });
//     // var image = await ImagePicker.pickImage(source: ImageSource.gallery);
//     // //_upLoadImage(image);//上传图片
//     // setState(() {
//     //   _image = image;
//     // });
//   }
//选择图片
  getimgs(type, index) async {
    var image;
    if (type == 1) {
      image = await ImagePicker.pickImage(source: ImageSource.gallery);
    } else {
      image = await ImagePicker.pickImage(source: ImageSource.camera);
    }
    if (image == null) return;
    // LoadingPage loadpage = new LoadingPage(context);
    // loadpage.show();
    File _files = await FlutterNativeImage.compressImage(image.path);

    Map<String, String> map = new Map();

    HttpHelper.upLoadImage(_files, (data) {
      //loadpage.close();
      print('data');
      if (data.containsKey('code')) {
        Toast.show(data['msg'], context);
      } else {
        if(index==1){
          //半身照片
          this.formList[1]['value']=data["url"];
          updateAvatar(data["attachment"],1);
        }else{
           this.formList[0]['value']=data["url"];
           updateAvatar(data["attachment"],0);
        }
        setState(() {
          formList=this.formList;
        });
      
      }
    }, params: map);

 
  }
updateAvatar(param,type) async{
  SharedPreferences pref = await SharedPreferences.getInstance();
Map<String, String> map = new Map();
    map["id"] = pref.getString('uid').toString();
    if(type==0){
      map['avatar']=param;
    }else{
       map['half_img']=param;
    }
     HttpHelper.post(HttpHelper.API_UpdateAvatar,(data) async {
      if (data != null) {
        print(data);
        Toast.show(data["msg"], context);

       
        
      }
    }, params: map);
   
}
//选择图片方式
  Future getImage(i) async {
    showDialog(
        context: context,
        builder: (BuildContext context) {
          return new SimpleDialog(
            title: new Text('选择'),
            children: <Widget>[
              new SimpleDialogOption(
                child: new Text('相机'),
                onPressed: () {
                  Navigator.pop(context);
                  getimgs(0, i);
                },
              ),
              new SimpleDialogOption(
                child: new Text('相册'),
                onPressed: () {
                  Navigator.pop(context);
                  getimgs(1, i);
                },
              )
            ],
          );
        });
    // var image = await ImagePicker.pickImage(source: ImageSource.gallery);
    // //_upLoadImage(image);//上传图片
    // setState(() {
    //   _image = image;
    // });
  }

  Widget build(BuildContext context) {
    return new Scaffold(
        key: _scaffoldKey,
        appBar: new AppBar(
          title: new Text('个人信息'),
          backgroundColor: Colors.white,
          elevation: 0,
          // backgroundColor: Color.fromRGBO(255, 204, 48, 1),
        ),
        body: new Center(
            child: Container(
                decoration: new BoxDecoration(
                  color: Color.fromRGBO(238, 238, 238, 1),
                ),
                child: Padding(
                    padding: new EdgeInsets.fromLTRB(0, 15, 0, 0),
                    child: Stack(
                      children: <Widget>[
                        Align(
                          alignment: Alignment.topCenter,
                          child: new ListView(children: <Widget>[layout()]),
                        ),
                        Align()
                      ],
                    )
                    // new ListView(
                    //   children: <Widget>[buildcontent()],
                    // )),
                    ))));
  }
}
